import { useEffect } from 'react';
import { ConfigProvider, theme, App as AntdApp } from 'antd';
import zhCN from 'antd/locale/zh_CN';
import enUS from 'antd/locale/en_US';
import { RouterProvider } from 'react-router-dom';
import { I18nextProvider } from 'react-i18next';
import router from './router';
import i18n from './i18n';
import { useThemeStore } from './stores/useThemeStore';
import { useSettingsStore } from './stores/useSettingsStore';
import 'dayjs/locale/zh-cn';
import './styles/global.css';

function App() {
  const { mode, primaryColor, isDark } = useThemeStore();
  const { language } = useSettingsStore();

  // 初始化主题
  useEffect(() => {
    const isDarkMode =
      mode === 'dark' || (mode === 'auto' && window.matchMedia('(prefers-color-scheme: dark)').matches);
    document.documentElement.classList.toggle('dark', isDarkMode);
    document.documentElement.style.setProperty('--primary-color', primaryColor);
  }, [mode, primaryColor]);

  // Ant Design 国际化配置
  const locale = language === 'zh-CN' ? zhCN : enUS;

  return (
    <I18nextProvider i18n={i18n}>
      <ConfigProvider
        locale={locale}
        theme={{
          algorithm: isDark() ? theme.darkAlgorithm : theme.defaultAlgorithm,
          token: {
            colorPrimary: primaryColor,
            borderRadius: 8,
          },
          components: {
            Layout: {
              siderBg: isDark() ? '#1a1a2e' : '#001529',
              triggerBg: isDark() ? '#16213e' : '#002140',
            },
            Menu: {
              darkItemBg: isDark() ? '#1a1a2e' : '#001529',
              darkSubMenuItemBg: isDark() ? '#16213e' : '#000c17',
            },
          },
        }}
      >
        <AntdApp
          message={{
            top: 80,
            duration: 3,
            maxCount: 3,
          }}
        >
          <RouterProvider router={router} />
        </AntdApp>
      </ConfigProvider>
    </I18nextProvider>
  );
}

export default App;
